﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Astronergy.MES.App.Library
{
    public class ImageHelper
    {
        /// <summary>
        /// 压缩原图片并保存
        /// </summary>
        /// <param name="sourcePath">原图片路径</param>
        /// <param name="aimPath">目标路径</param>
        public void SaveCompressPic(string sourceFilePath, string aimFilePath)
        {
            byte[] bytes = Getbytes(sourceFilePath);

            using (MemoryStream ms = new MemoryStream(bytes))
            {
                Image img = Image.FromStream(ms);
                img.Save(aimFilePath, ImageFormat.Jpeg);
            }
        }

        /// <summary>
        /// 获取压缩后的图片流信息
        /// </summary>
        /// <param name="imgePath">图片路径</param>
        /// <returns>压缩后的图片流信息</returns>
        private byte[] Getbytes(string imgePath)
        {
            byte[] buffer = null;

            using (Stream s = File.OpenRead(imgePath))
            {
                buffer = new byte[s.Length];
                s.Read(buffer, 0, (int)s.Length);
                s.Close();
            }

            return CompressPic(buffer);
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="buffer">图片数据流信息</param>
        /// <returns>压缩后的图片数据流信息</returns>
        private byte[] CompressPic(byte[] buffer)
        {
            if (buffer != null)
            {
                try
                {
                    using (MemoryStream msImage = new MemoryStream())
                    {
                        msImage.Write(buffer, 0, buffer.Length);
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (System.Drawing.Image img = System.Drawing.Image.FromStream(msImage))
                            {
                                int width = 450;
                                int heigth = (int)Math.Ceiling(img.Height / (img.Width / (width + 0.0)));
                                Image destImag = new Bitmap(img, new Size(width, heigth));
                                destImag.Save(ms, ImageFormat.Jpeg);
                                buffer = ms.GetBuffer();
                            }
                        }
                    }
                }
                catch (Exception ex)
                { }
            }
            return buffer;
        }
    }
}
